package com.topscomm.mpm.controller;

import cn.hutool.core.date.DateUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.ICboModuleLogService;
import com.topscomm.mis.service.IMisModuleLogDailyStatisticsService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liwanpeng
 * @version 1.0
 * @description: 数据统计
 * @date 2021/1/15 19:12
 */
@RestController
@RequestMapping("/mpm/mpmStatisticsContoller")
public class MpmStatisticsContoller {
    @Autowired
    private ICboModuleLogService cboModuleLogService;
    @Autowired
    private IMisModuleLogDailyStatisticsService misModuleLogDailyStatisticsService;
    @GetMapping("/moudleLogStatistics")
    public ResponseResult<Object> moudleLogStatistics(@RequestParam(required = false) Map<String, Object> param) {
        StringBufferProxy sql = new StringBufferProxy();
        StringBufferProxy whereSqlForCalendar = new StringBufferProxy();
        sql.appendSingle("1=1");
        if (param.containsKey("deptName")) {
            String value = ConvertUtil.convertToString(param.get("deptName"));
            sql.appendSingle(" and exists(select id from cbouser where cboUser.code = MISMODULELOGDAILYSTATISTICS.operateusercode and exists (select id from cboDept where cboDept.id = cboUser.deptid and cboDept.name like '%{0}%')) ", value);
        }
        if (param.containsKey("cboModuleCode")) {
            String value = ConvertUtil.convertToString(param.get("cboModuleCode"));
            sql.appendSingle(" and MISMODULELOGDAILYSTATISTICS.modulecode = '{0}' ", value);
        }
        if (param.containsKey("userCode")) {
            String value = ConvertUtil.convertToString(param.get("userCode"));
            sql.appendSingle(" and exists(select id from cbouser where cboUser.code = MISMODULELOGDAILYSTATISTICS.operateusercode and cboUser.code = '{0}') ", value);
        }
        // 开始时间
        Date startDate = null;
        if (param.containsKey("startDate")) {
            String value = ConvertUtil.convertToString(param.get("startDate"));
            sql.appendSingle(" and MISMODULELOGDAILYSTATISTICS.statisticdate >= {0}", SQLAdapter.toDateShort(value));
            startDate = DateUtil.parseDate(value);
        } else {
            // 如果没有开始时间，默认一个月前为开始时间
            startDate = DateUtil.offsetMonth(new Date(), -1);
            sql.appendSingle(" and cboModuleLog.operateDate >= {0}", SQLAdapter.toDateShort(DateUtil.formatDate(startDate)));

        }
        // 结束时间
        Date endDate = null;
        if (param.containsKey("endDate")) {
            String value = ConvertUtil.convertToString(param.get("endDate"));
            sql.appendSingle(" and MISMODULELOGDAILYSTATISTICS.startDate = DateUtil.parseDate(value); <= {0}", SQLAdapter.toDateShort(value));
            endDate = DateUtil.parseDate(value);
        } else {
            // 如果没有结束时间，默认当前为结束时间
            endDate = new Date();
            sql.appendSingle(" and cboModuleLog.operateDate <= {0}", SQLAdapter.toDateShort(DateUtil.formatDate(endDate)));
        }
        Query query = new Query(param);
        Map<String, Object> countParam = new HashMap<>();
        countParam.put("whereSql", sql.toString());
        countParam.put("begincount", ConvertUtil.convertToLong(param.get("pageSize")) * ConvertUtil.convertToLong(param.get("currentPage")) - ConvertUtil.convertToLong(param.get("pageSize")));
        countParam.put("pagesize", ConvertUtil.convertToLong(param.get("pageSize")));
        int totalCount = misModuleLogDailyStatisticsService.getCount(countParam, "moduleLogStatiSticCountByUser");
        List<Map<String, Object>> listFromDb = misModuleLogDailyStatisticsService.queryMap(countParam, "moduleLogStatiSticByUser");
        Page page = new Page(listFromDb, totalCount, query.getPageSize(), query.getCurrentPage());
        return ResponseResult.ok(page);
    }
//    @GetMapping("/moudleLogStatistics")
//    public ResponseResult<Object> moudleLogStatistics(@RequestParam(required = false) Map<String, Object> param) {
//        StringBufferProxy sql = new StringBufferProxy();
//        StringBufferProxy whereSqlForCalendar = new StringBufferProxy();
//        sql.appendSingle("1=1");
//        if (param.containsKey("deptName")) {
//            String value = ConvertUtil.convertToString(param.get("deptName"));
//            sql.appendSingle(" and exists(select id from cbouser where cboUser.id = cboModuleLog.operateUser and exists (select id from cboDept where cboDept.id = cboUser.deptid and cboDept.name like '%{0}%')) ", value);
//        }
//        if (param.containsKey("cboModuleCode")) {
//            String value = ConvertUtil.convertToString(param.get("cboModuleCode"));
//            sql.appendSingle(" and cboModuleLog.MODULENAME = '{0}' ", value);
//        }
//        if (param.containsKey("userCode")) {
//            String value = ConvertUtil.convertToString(param.get("userCode"));
//            sql.appendSingle(" and exists(select id from cbouser where cboUser.id = cboModuleLog.operateUser and cboUser.code = '{0}') ", value);
//        }
//        // 开始时间
//        Date startDate = null;
//        if (param.containsKey("startDate")) {
//            String value = ConvertUtil.convertToString(param.get("startDate"));
//            sql.appendSingle(" and cboModuleLog.operateDate >= {0}", SQLAdapter.toDateShort(value));
//            whereSqlForCalendar.appendSingle("  CBOWORKINGCALENDAR.SALARYDAY >= {0}", SQLAdapter.toDateShort(value));
//
//            startDate = DateUtil.parseDate(value);
//        } else {
//            // 如果没有开始时间，默认一个月前为开始时间
//            startDate = DateUtil.offsetMonth(new Date(), -1);
//            sql.appendSingle(" and cboModuleLog.operateDate >= {0}", SQLAdapter.toDateShort(DateUtil.formatDate(startDate)));
//            whereSqlForCalendar.appendSingle("  CBOWORKINGCALENDAR.SALARYDAY >= {0}", SQLAdapter.toDateShort(DateUtil.formatDate(startDate)));
//
//        }
//        // 结束时间
//        Date endDate = null;
//        if (param.containsKey("endDate")) {
//            String value = ConvertUtil.convertToString(param.get("endDate"));
//            sql.appendSingle(" and cboModuleLog.operateDate <= {0}", SQLAdapter.toDateShort(value));
//            endDate = DateUtil.parseDate(value);
//            whereSqlForCalendar.appendSingle(" and CBOWORKINGCALENDAR.SALARYDAY <= {0}", SQLAdapter.toDateShort(value));
//
//        } else {
//            // 如果没有结束时间，默认当前为结束时间
//            endDate = new Date();
//            sql.appendSingle(" and cboModuleLog.operateDate <= {0}", SQLAdapter.toDateShort(DateUtil.formatDate(endDate)));
//            whereSqlForCalendar.appendSingle(" and CBOWORKINGCALENDAR.SALARYDAY <= {0}", SQLAdapter.toDateShort(DateUtil.formatDate(endDate)));
//        }
//        Query query = new Query(param);
//        Map<String, Object> countParam = new HashMap<>();
//        countParam.put("whereSql", sql.toString());
//        countParam.put("userCode", ConvertUtil.convertToString(param.get("userCode")));
//        countParam.put("userName", ConvertUtil.convertToString(param.get("userName")));
//        countParam.put("moduleCode", ConvertUtil.convertToString(param.get("moduleCode")));
//        countParam.put("moduleName", ConvertUtil.convertToString(param.get("moduleName")));
//        countParam.put("begincount", ConvertUtil.convertToLong(param.get("pageSize")) * ConvertUtil.convertToLong(param.get("currentPage")) - ConvertUtil.convertToLong(param.get("pageSize")));
//        countParam.put("pagesize", ConvertUtil.convertToLong(param.get("pageSize")));
//        countParam.put("whereSqlForCalendar", whereSqlForCalendar.toString());
//        int totalCount = this.cboModuleLogService.getCount(countParam, "moduleLogStatiSticCountByUser");
//        List<Map<String, Object>> listFromDb = cboModuleLogService.queryMap(countParam, "moduleLogStatiSticByUser");
//        Page page = new Page(listFromDb, totalCount, query.getPageSize(), query.getCurrentPage());
//        return ResponseResult.ok(page);
//    }

    //    @GetMapping("/moudleLogStatistics")
//    public ResponseResult<Object> moudleLogStatistics(@RequestParam(required = false) Map<String, Object> param) {
//        StringBufferProxy sql = new StringBufferProxy();
//        sql.appendSingle("1=1" );
//        if (param.containsKey("deptName")) {
//            String value = ConvertUtil.convertToString(param.get("deptName"));
//            sql.appendSingle(" and exists(select id from cbouser where cboUser.id = cboModuleLog.operateUser and exists (select id from cboDept where cboDept.id = cboUser.deptid and cboDept.name like '%{0}%')) ", value);
//        }
//        if (param.containsKey("cboModuleCode")) {
//            String value = ConvertUtil.convertToString(param.get("cboModuleCode"));
//            sql.appendSingle(" and cboModuleLog.MODULENAME = '{0}' ", value);
//        }
//        if (param.containsKey("user")) {
//            String value = ConvertUtil.convertToString(param.get("user"));
//            sql.appendSingle(" and exists(select id from cbouser where cboUser.id = cboModuleLog.operateUser and cboUser.name like '%{0}%') ", value);
//        }
//        // 开始时间
//        Date startDate = null;
//        if (param.containsKey("startDate")) {
//            String value = ConvertUtil.convertToString(param.get("startDate"));
//            sql.appendSingle(" and cboModuleLog.operateDate > {0}", SQLAdapter.toDateShort(value));
//            startDate = DateUtil.parseDate(value);
//        } else {
//            // 如果没有开始时间，默认一个月前为开始时间
//            startDate = DateUtil.offsetMonth(new Date(), -1);
//            sql.appendSingle(" and cboModuleLog.operateDate > {0}", SQLAdapter.toDateShort(DateUtil.formatDate(startDate)));
//
//        }
//        // 结束时间
//        Date endDate = null;
//        if (param.containsKey("endDate")) {
//            String value = ConvertUtil.convertToString(param.get("endDate"));
//            sql.appendSingle(" and cboModuleLog.operateDate < {0}", SQLAdapter.toDateShort(value));
//            endDate = DateUtil.parseDate(value);
//        } else {
//            // 如果没有结束时间，默认当前为结束时间
//            endDate = new Date();
//            sql.appendSingle(" and cboModuleLog.operateDate < {0}", SQLAdapter.toDateShort(DateUtil.formatDate(endDate)));
//        }
//        Query query = new Query(param);
//        Map<String,Object> countParam = new HashMap<>();
//        countParam.put("whereSql",sql.toString());
//        int totalCount = this.cboModuleLogService.getCount( countParam,"moduleLogStatiSticCount");
//        List<Map<String, Object>> listFromDb = cboModuleLogService.queryMapForPage(sql.toString(), query.getCurrentPage(), query.getPageSize(),
//                query.getSidx(), query.getSord(),"moduleLogStatiStic");
//        // 遍历list，对缺失的日期进行补全
//        // 补全逻辑：由于list为已经排好序、分好组的列表，故只需要在同一个用户下判断日期是否连续
//        List<Map<String, Object>> cloneList = ObjectUtil.clone(listFromDb);
//        String userCodeAndModulCodeAndDate = "";
//        Date dateCurrent = ObjectUtil.clone(startDate);
//        for (int i = 0; i < listFromDb.size(); i++) {
//            Map<String, Object> tempMap = listFromDb.get(i);
//            String userCodeAndModulCodeAndDateTemp = ConvertUtil.convertToString(tempMap.get("usercode")) + "," + ConvertUtil.convertToString(tempMap.get("modulecode")) ;
//            // 如果当前数据的，用户code，模块code的组合字符串和上一次的不一样，则需要以开始日期为起点进行数据补全
//            if (!userCodeAndModulCodeAndDateTemp.equals(userCodeAndModulCodeAndDate)) {
//                // 补全开始日期到此日期的时间
//                while (dateCurrent.getTime() < DateUtil.parseDate(ConvertUtil.convertToString(listFromDb.get(i).get("operateDate"))).getTime()) {
//                    // 组装新的map并添加到此列表尾部
//                    Map<String, Object> tempMapForAdd = ObjectUtil.clone(tempMap);
//                    tempMapForAdd.put("operateDate", DateUtil.formatDate(dateCurrent));
//                    tempMapForAdd.put("clickcount", 0);
//                    cloneList.add(tempMapForAdd);
//                    dateCurrent = DateUtil.offsetDay(dateCurrent, 1);
//                }
//                // 日期游标需要加2天
//                dateCurrent = DateUtil.offsetDay(dateCurrent, 1);
//                // 判断是否
//            } else if (userCodeAndModulCodeAndDateTemp.equals(userCodeAndModulCodeAndDate)) {
//                // 如果本次循环和上次循环的用户code，模块code的组合字符串和上一次的相同，则需要补全dateCurrent和本次循环之间的日期数据，
//                // 补全开始日期到此日期的时间
//                while (dateCurrent.getTime() < DateUtil.parseDate(ConvertUtil.convertToString(listFromDb.get(i).get("operateDate"))).getTime()) {
//                    // 组装新的map并添加到此列表尾部
//                    Map<String, Object> tempMapForAdd = ObjectUtil.clone(tempMap);
//                    tempMapForAdd.put("operateDate", DateUtil.formatDate(dateCurrent));
//                    tempMapForAdd.put("clickcount", 0);
//                    cloneList.add(tempMapForAdd);
//                    dateCurrent = DateUtil.offsetDay(dateCurrent, 1);
//                }
//                // 日期游标需要加1天
//                dateCurrent = DateUtil.offsetDay(dateCurrent, 1);
//            }
//            if(i==listFromDb.size()-1||!userCodeAndModulCodeAndDateTemp.equals(ConvertUtil.convertToString(listFromDb.get(i+1).get("usercode")) + "," + ConvertUtil.convertToString(listFromDb.get(i+1).get("modulecode")))){
//                //如果本次循环和下一个元素的用户code，模块code和日期的组合字符串不同，或者没有下一个元素时，则需要补全本次循环到结束日期之间的数据且日期游标恢复到起始日期
//                // 补全本次循环的日期到结束日期的数据
//                while (dateCurrent.getTime() < endDate.getTime()) {
//                    // 组装新的map并添加到此列表尾部
//                    Map<String, Object> tempMapForAdd = ObjectUtil.clone(tempMap);
//                    tempMapForAdd.put("operateDate", DateUtil.formatDate(dateCurrent));
//                    tempMapForAdd.put("clickcount", 0);
//                    cloneList.add(tempMapForAdd);
//                    dateCurrent = DateUtil.offsetDay(dateCurrent, 1);
//                }
//                // 日期游标恢复到起始日期
//                dateCurrent = ObjectUtil.clone(startDate);
//            }
//            userCodeAndModulCodeAndDate=userCodeAndModulCodeAndDateTemp;
//        }
//
//        List<Map<String, Object>> collect = cloneList.stream().sorted(Comparator.comparing(MpmStatisticsContoller::compareUsercode).thenComparing(MpmStatisticsContoller::compareOperateDate).thenComparing(MpmStatisticsContoller::compareModulecode)).collect(Collectors.toList());
//        Page page = new Page(collect, totalCount, query.getPageSize(), query.getCurrentPage());
//        return ResponseResult.ok(page);
//    }
    public static String compareUsercode(Map<String, Object> o) {
        String str = ConvertUtil.convertToString(o.get("usercode"));
        return str;
    }

    public static String compareModulecode(Map<String, Object> o) {
        String str = ConvertUtil.convertToString(o.get("compareModulecode"));
        return str;
    }

    public static String compareOperateDate(Map<String, Object> o) {
        String str = ConvertUtil.convertToString(o.get("operateDate"));
        return str;
    }
}
